package gr.anagnosg.general.utils;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.apache.tools.ant.DirectoryScanner;
public class FileUtils {
    public FileUtils() {
        super();
    }

    public  static boolean  copyfiles(String srFile, String dtFile) throws  IOException, FileNotFoundException{
        File f1 = new File(srFile);
        File fout = new File(dtFile);
        if(fout.exists() && fout.length()==f1.length()){
            //sthn periptosi pou uparxei to fout hdh kai exei to idio mege8os tote den kano tipota.
            return false;
        }
        InputStream in = null;
        OutputStream out = null;
        
          try{
              //Log.log("srFile"+srFile+",dtFile "+dtFile, Log.LOG_ALL);

              in = new FileInputStream(f1);

              //For Overwrite the file.
              out = new FileOutputStream(dtFile);
        
              byte[] buf = new byte[1024];
              int len;
              while ((len = in.read(buf)) > 0){
                out.write(buf, 0, len);
              }
              
              //System.out.println("File copied.");
          }
          finally{
              if(in!=null){
                in.close();
              }
              if(out!=null){
                out.close();
              }
          }
          
          return true;
    }
    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if(files!=null) { //some JVMs return null for empty dirs
            for(File f: files) {
                if(f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
    
    
    public static void deleteFiles(File[] f ){
        for(int i=0; i < f.length ; i ++){
            File ft = f[i];
            ft.delete();
        }
    }

    public static String getFilenameNoExt(File f){
        String filename = f.getName();
        String output = filename;
        if(filename.lastIndexOf(".")>-1){
            output=filename.substring(0,filename.lastIndexOf("."));
        }
        return output;
    
    }   
    
    public static String fileDiff(String t1,String t2){
        
        String diff = org.apache.commons.lang3.StringUtils.difference(t1, t2);
        System.out.println(diff);
        return diff;
    }
    
    public static String  readTextFile(FileReader input) {
        String output = "";
		BufferedReader br = null;
 
		try {
 
			String sCurrentLine;
 
			br = new BufferedReader(input);
 
			while ((sCurrentLine = br.readLine()) != null) {
				//System.out.println(sCurrentLine);
                            output+=sCurrentLine+"\n";
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)br.close();
                                if(input!=null)input.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
                return output;
    }
    public static String  readTextFile(File f)  {
        FileReader fr = null;
        try{
            fr = new FileReader(f);
        }
        catch(FileNotFoundException ex){
            ex.printStackTrace();
        }
        return readTextFile( fr);
    }
    public static String  readTextFile(String fullFilename)  {
        File f=null;
      
        f = new File(fullFilename);        
        return readTextFile(f);
 
    }
    
    
    
    public static void concatTextFiles(String f1,String f2){
        String uid = UUID.randomUUID().toString(); 
        String f1tmp = f1+uid;
        try{
            if(!(new File(f1).exists())){File f1t = new File(f1);f1t.createNewFile();}
            InputStream in = new FileInputStream(f1);
            byte[] buffer = new byte[1 << 20];  // loads 1 MB of the file
            OutputStream os = new FileOutputStream(new File(f1tmp), true);
            int count;
            while ((count = in.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
            in.close();
            in = new FileInputStream(f2);
            while ((count = in.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
            in.close();
            os.close();
            File deleteF = new File(f1);
            deleteF.delete();
            File frename = new File(f1tmp);
            frename.renameTo(new File(f1));
        }
        catch(Exception ex){
        ex.printStackTrace();
        }
        
        
    }
    public static String concatTextFileArray(File files[]){
        String outputFile= "";
        String parentStr = files[0].getParent();
        String filenameStr = files[0].getName();
        String newFileName = filenameStr.replaceAll("_p\\d", "_all");
        outputFile = parentStr +File.separatorChar+newFileName;
        
        File f = new File(outputFile);
        for(int i = 0 ; i<files.length ; i ++){
            File ft = files[i];
            String f1 = f.getAbsolutePath();String f2 = ft.getAbsolutePath();
            //System.out.println("f1"+f1+",f2"+f2);
            concatTextFiles(f1,f2);
        }
        return outputFile;
    }
    
    public static File[] orderByPage(File[] files){
        File output[] = new File[files.length];
        for(int i=0;i<files.length;i++){
            for(int j=0;j<files.length;j++){
                File ft = files[j];
                String filename = ft.getName();
                if(filename.indexOf("_p"+i)>=0){
                    output[i]=files[j];
                    break;
                }
            }
        }
        return output;
    }
    
    
    /*public static void renamefile(String filename,String filenameNew){
         File ft = new File(filename);ft.renameTo(filenameNew);
         //String prefix = ft.getParent()+File.pathSeparatorChar;
         String command="mv "+filename+" " + filenameNew;
         String output = ExtrernalUtils.executeCommand(command);
                
    }*/
    
    public static long calcTotalSize(String files[]){
        long total = 0;
        for(int i=0;i<files.length;i++){
            String fStr = files[i];
            File f =  new File(fStr);
            int j=0;
            
            while (f.length()==0 && j<100 ){
                try{
                    //System.out.println("File"+f.getName()+" size is 0.");
                    Thread.sleep(100);
                }
                catch(Exception ex){
                    ex.printStackTrace();
                }
                j++;
            }
            //System.out.println("file "+f.getName()+" ,size"+f.length());
            total+=f.length();
        }
        return total;
    }
    
    public static String changeExtension(String filename, String newExtension){
        File fT = new File(filename);
        String parent   = fT.getParent();
        String filenameNew = FileUtils.getFilenameNoExt(new File(filename));
        String output = "";
        if(parent!=null){
            output= parent+File.separatorChar+filenameNew+"."+newExtension;
        }
        else{
            output =filenameNew+"."+newExtension;
        }
        return output;
        
    }
    
    public static boolean isTiff(String filename){
        String ext = FileUtils.getExtension(filename);
        if(ext.equalsIgnoreCase("tiff") || ext.equalsIgnoreCase("tif")){
            return true;
        }
        else{
            return false;
        }
        
    }
    public static String getExtension(String filename){
        String extension ="";
        if(filename.lastIndexOf(".")>0){
            int index = filename.lastIndexOf(".");
            extension = filename.substring(index+1,filename.length());
        }
        
        
        return extension;
        
    }
    
    
    public static String[] findMatchingDirs(String searchStr){
        int indexOfLastFileSeperator = searchStr.lastIndexOf(File.separatorChar);
        String parentStr =  searchStr.substring(0,indexOfLastFileSeperator)+File.separatorChar;
        String restStr = searchStr.substring(indexOfLastFileSeperator+1,searchStr.length());
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setIncludes(new String[]{restStr+"*"});
        scanner.setBasedir(parentStr);

        scanner.setCaseSensitive(true);
        scanner.scan();
        String[] files = scanner.getIncludedDirectories();
        return files;
        
    }
    public static void main(String args[]){
        
    }
}
